package com.jiaanpei.frameproject.modle.bean.base;

import com.jiaanpei.frameproject.base.BaseActivity;
import com.jiaanpei.frameproject.manage.Navigate;
import com.jiaanpei.frameproject.utils.ToastUtil;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public abstract class CallBackListener<T> implements Callback<BaseResponse<T>> {
    private BaseActivity mBaseActivity;
    private boolean showLoding;

    public CallBackListener(BaseActivity baseActivity, boolean showLoding) {
        this.mBaseActivity = baseActivity;
        this.showLoding = showLoding;
        if (showLoding){
            if(mBaseActivity!=null){
                mBaseActivity.startLoading("加载中...");
            }
        }

    }

    protected abstract void onSuccess(BaseResponse<T> result);

    protected void requestError(String error) {
        if (mBaseActivity != null)
            ToastUtil.show(mBaseActivity, error);
    }

    @Override
    public void onResponse(Call<BaseResponse<T>> call, Response<BaseResponse<T>> response) {
        if (showLoding && mBaseActivity != null)
            mBaseActivity.stopLoading();

        if (response == null) {
            return;
        }
        BaseResponse<T> body = response.body();

        if (body == null || body.head == null) {
            requestError("数据异常");
            return;
        }
        String errMsg = body.head.errMsg;
        if ("未登陆".equals(errMsg)) {
            Navigate.startLoginActivity(mBaseActivity);
            requestError(errMsg);
            return;
        }


        if ("000".equals(body.head.errCode) && body.isSuccess()) {
            onSuccess(body);
        } else {
            requestError(errMsg);
        }
    }

    @Override
    public void onFailure(Call<BaseResponse<T>> call, Throwable t) {
        if (showLoding && mBaseActivity != null)
            mBaseActivity.stopLoading();
        requestError(t.getMessage());

    }
}
